package zb.WX.util;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送https请求和接收的返回的结果
 *
 * @author Administrator
 */
public class HttpsUtil {
    /*
     * 发送数据并返回json
     */
    public static String getHttpsToJson(String urlStr, String jsonStr) {
        try {
            //发送https请求到微信端
            URL url = new URL(urlStr);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();

            //当需要发送数据时才执行下面的代码
            if (jsonStr != null) {
                httpsConn.setDoOutput(true);
                OutputStreamWriter osw = new OutputStreamWriter(httpsConn.getOutputStream(), "UTF-8");
                osw.write(jsonStr);//如果没有数据则发送null过去
                osw.close();
            }

            //输出返回的结果
            InputStreamReader isr = new InputStreamReader(httpsConn.getInputStream(), "UTF-8");
            String result = "";
            char[] c = new char[1024];
            int len;
            while ((len = isr.read(c)) != -1) {
                result += new String(c, 0, len);
            }
            System.out.println();
            System.out.println("返回结果：" + result);
            System.out.println();
            isr.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 下载素材
     *
     * @param urlStr
     * @return
     * @throws IOException
     */
    public static boolean getMaterial(String urlStr) throws IOException {
        URL u = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("POST");
        conn.connect();
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        String content_disposition = conn.getHeaderField("content-disposition");
        if (content_disposition == null) {
            return false;
        }
        String file_name = "";
        String[] content_arr = content_disposition.split(";");
        if (content_arr.length == 2) {
            String tmp = content_arr[1];
            int index = tmp.indexOf("\"");
            file_name = tmp.substring(index + 1, tmp.length() - 1);
        }
        File file = new File(PropertiesUtil.getPropValue("demo.fileinputupload.path") + File.separator + file_name);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[2048];
        int length = bis.read(buf);
        while (length != -1) {
            bos.write(buf, 0, length);
            length = bis.read(buf);
        }
        bos.close();
        bis.close();
        return true;
    }
}
